<template>
  <div>
    <hr>
    <div class="clearfix">
      <el-button size="small" class="pull-right" @click="fieldModal=true">编辑视图</el-button>
      数据预览
    </div>
    <hr>
    <el-table border :data="dataSet.data" v-if=" dataSet.series.length>0"
              :height="tableHeight"
              @filter-change="pickColMenu" style="min-width:100%;">
      <el-table-column v-for="item in dataSet.series" :label="item.title" :key="item.id" :render-header="formatHeader"
                       align="center" sortable :prop="item.id"
                       :filters="item.filterArr"
                       :filter-multiple="false"
                       :filter-method="filterTag" :clearFilter="false" filter-placement="bottom" width="200">

      </el-table-column>
    </el-table>

    <el-dialog
      title="编辑字段"
      :visible.sync="fieldModal"
      width="600px" append-to-body>
      <div>
        <div class="join-form no-radius">
          <el-row type="flex">
            <el-col :span="2">
              隐藏
            </el-col>
            <el-col :span="6">
              字段
            </el-col>
            <el-col :span="6">
              别名
            </el-col>
            <el-col :span="4">
              类别
            </el-col>
            <el-col :span="6">
              计算方法
            </el-col>
          </el-row>

          <el-row type="flex" v-for="(item,index) in fieldList" style="align-items: center" :key="index">
            <el-col :span="2">
              <el-switch v-model="item.hidden" :active-value="0" :inactive-value="1"></el-switch>
            </el-col>
            <el-col :span="6">
              <el-input type="text" readonly size="small" v-model="item.name"></el-input>

            </el-col>
            <el-col :span="6">
              <el-input type="text" size="small" v-model="item.title" placeholder="请输入"></el-input>
            </el-col>
            <el-col :span="4">
              <el-select size="small" v-model="item.stype" placeholder="请选择" :disabled="item.viewId!==''">
                <el-option value="d" label="维度"></el-option>
                <el-option value="m" label="度量"></el-option>
              </el-select>
            </el-col>
            <el-col :span="6" v-if="item.stype==='m'">
              <el-select size="small" v-model="item.functionName" placeholder="请选择">
                <el-option :label="fun.title" :value="fun.name" :key="fun.name" v-for="fun in aggregateFunList">
                </el-option>
              </el-select>
            </el-col>
          </el-row>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button @click="fieldModal = false">取 消</el-button>
        <el-button type="primary" @click="saveFields">确 定</el-button>
      </div>
    </el-dialog>
    <d-tom-dialog :show="showFieldD2M" :field="fieldD2M" @close="changeD2M"></d-tom-dialog>
  </div>
</template>

<script type="text/jsx">
  import {http, measure, dimension, field} from '@/resources';
  import opera from '@/action/opera';
  import DTomDialog from '../../action/dTomDialog.vue';

  export default {
    components: {DTomDialog},
    props: {},
    data: function () {
      return {
        fieldModal: false,
        fieldList: [],
        orgFieldList: [],
        dataSet: {
          series: [],
          data: []
        },
        currentTab: 'data',
        showRight: false,
        formTitle: '修改',
        action: 'add',
        form: {},
        isChange: false,
        changeCount: 0,
        fieldD2M: {},
        showFieldD2M: false
      };
    },
    computed: {
      pathUrl: function () {
        return `/project/${this.$route.params.projectId}/chart/${this.$route.params.chartId}`;
      },
      currentDatasetId() {
        return this.$store.state.currentDatasetId;
      },
      chartId() {
        return this.$route.params.chartId;
      },
      tableHeight() {
        return this.$store.state.bodyHeight - 250;
      },
      aggregateFunList() {
        return this.$store.state.aggregateFunList;
      }
    },
    mounted() {
      this.getFields();
    },
    watch: {
      currentDatasetId: function () {
        this.getFields();
      },
      changeCount: function (s) {
        if (s === this.fieldList.length) {
          this.getSeries();
        }
      }

    },
    methods: {
      changeD2M() {
        this.showFieldD2M = false;
        this.getFields();
      },
      pickColMenu(operaFlag) {
        let operaObj = Object.values(operaFlag);
        if (operaObj && operaObj[0] && operaObj[0][0]) {
          let operaStr = operaObj[0][0];
          let operaInfoObj = operaStr.split('||');
          let viewId = operaInfoObj[1];
          let currentFeild = this.fieldList.filter(item => {return item.viewId === viewId;})[0];
          let modal;
          if (currentFeild.stype === 'd') {
            modal = dimension;
          } else {
            modal = measure;
          }
          if (operaInfoObj.length === 2) {
            switch (operaInfoObj[0]) {
              case 'rename':
                opera.rename(modal, currentFeild.viewId, currentFeild.title).then(res => {
                  this.getFields();
                });
                break;
              case 'hidden':
                opera.delete(modal, viewId).then(res => {
                  this.getFields();
                });
                break;
              case 'm':

              case 'cm':
                this.fieldD2M = field;
                this.showFieldD2M = true;
                break;
              case 'd':
                opera.dTom(currentFeild, this).then(res => {
                  this.getFields();
                });

                break;

              default:
                break;
            }
          }
        }
      },
      filterTag(value, row) {
        return true;
      },
      resetRightBox() {
        this.showRight = false;
      },
      showRightPart() {
        this.showRight = true;
      },
      getFunctionList() {

      },
      formatHeader(h, col) {
        let index = col.$index;
        return (
          <span style="color:#333;">{col.column.label}</span>

        );
      },
      saveFields() {
        this.changeCount = 0;
        this.fieldList.forEach((item, index) => {
          if (item.stype === 'm' && item.name === item.title) {
            item.title = item.name + '(' + item.functionName + ')';
          }
          if (!item.viewId) {
            if (item.hidden === 0) { // add
              if (item.stype === 'd') {
                dimension.save({
                  title: item.title,
                  fieldId: item.id
                }).then(res => {
                  item.viewId = res.data.dimensionId;
                  this.changeCount++;
                });
              } else if (item.stype === 'm') {
                measure.save({
                  'fieldId': item.id,
                  'title': item.title,
                  'functionName': item.functionName
                }).then(res => {
                  item.viewId = res.data.measureId;
                  this.changeCount++;
                });
              }
            } else {
              this.changeCount++;
            }

          } else {
            if (item.hidden) { // delete
              if (item.stype === 'd') {
                dimension.delete(item.viewId).then(res => {
                  item.viewId = '';
                  this.changeCount++;
                });
              } else if (item.stype === 'm') {
                measure.delete(item.viewId).then(res => {
                  item.viewId = '';
                  this.changeCount++;
                });
              }
            } else { // update
              if (item.stype === 'd') {
                dimension.update(item.viewId, {
                  title: item.title,
                  fieldId: item.id
                }).then(res => {
                  this.changeCount++;
                });
              } else if (item.stype === 'm') {
                measure.update(item.viewId, {
                  'fieldId': item.id,
                  'title': item.title,
                  'functionName': item.functionName
                }).then(res => {
                  this.changeCount++;
                });
              } else {
                this.changeCount++;
              }
            }
          }

        });
        this.fieldModal = false;
      },
      getFields() {
        http.get('/fieldview', {params: {datasetId: this.currentDatasetId}}).then(res => {
          res.data.data.forEach(item => {
            let stype = '';
            let hidden = 1;
            if (item.viewId) {
              hidden = 0;
            }
            item.hidden = hidden;
            stype = item.functionName ? 'm' : 'd';

            item.stype = stype;
          });
          this.fieldList = res.data.data;
          this.getSeries();
        });
      },
      getSeries() {
        let series = [];
        let operaFlag = '||';
        this.fieldList.forEach(item => {
          let operaFlag = '||' + item.viewId;
          if (item.viewId) {
            let filterArr = [
              {
                text: '隐藏',
                value: 'hidden' + operaFlag
              },
              {
                text: '重命名',
                value: 'rename' + operaFlag
              }
            ];
            if (item.stype === 'd') {
              filterArr.push({text: '转换为度量', value: 'm' + operaFlag});
            } else {
              filterArr.push({text: '转换为维度', value: 'd' + operaFlag});
              filterArr.push({text: '更换计算方法', value: 'cm' + operaFlag});
            }
            series.push({
              id: item.viewId,
              name: item.name,
              title: item.title,
              stype: item.stype,
              filterArr
            });
          }
        });
        this.dataSet.series = series;
        this.getData();
      },
      getData() {
        if (this.dataSet.series.length === 0) {
          return false;
        }
        let data = [];
        let postData = {
          'dimension': [],
          'measure': []
        };
        this.dataSet.series.forEach(item => {
          if (item.stype === 'm') {
            postData.measure.push(item.id);
          } else {
            postData.dimension.push(item.id);
          }
        });
        http.post(`/data/${this.chartId}`, postData).then(res => {
          this.dataSet.data = res.data.data;
        });
      }
    }
  };
</script>
